define(['jquery', 'bootstrap', 'backend', 'table', 'form','echarts'], function ($, undefined, Backend, Table, Form, echarts) {


    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'node/nodeflow/index',
                    add_url: 'node/nodeflow/add',
                    edit_url: 'node/nodeflow/edit',
                    del_url: 'node/nodeflow/del',
                    multi_url: 'node/nodeflow/multi',
                    table: 'flow_statistics',
                }
            });
            if(!Fast.api.query('starttime') && !Fast.api.query('endtime')){
                $("#start_date").val(start_time);
                $("#end_date").val(end_time);
            }
            require(['bootstrap-datetimepicker','moment'], function (undefined,moment) {
                $('#start_date').datetimepicker({
                    locale: moment.locale('zh-cn') //引入中文语言
                    // language:  'zh-CN',  //日期
                });
                $('#end_date').datetimepicker({
                  locale: moment.locale('zh-cn') //引入中文语言
                });
            });
            var table = $("#table");

            // 初始化表格
            // table.bootstrapTable({
            //     url: $.fn.bootstrapTable.defaults.extend.index_url,
            //     pk: 'id',
            //     sortName: 'id',
            //     columns: [
            //         [
            //             {checkbox: true},
            //             {field: 'ip', title: __('Ip')},
            //             {field: 'flow_rx', title: __('Flow_rx')},
            //             {field: 'flow_tx', title: __('Flow_tx')},
            //             {field: 'tcp_connection_num', title: __('Tcp_connection_num')},
            //             {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
            //         ]
            //     ]
            // });

            require(['bootstrap-select', 'bootstrap-select-lang'], function () {
                $('.selectpicker').selectpicker('refresh');
                
            })
            $.ajax({
                url: 'node/nodeflow/index',
                type:'get',
                dataType:'json',
                data: {starttime:$("#start_date").val(),endtime:$("#end_date").val(),typename:$("#typename").val(),compare:$("#compare").val(),ip:$("#ip").val()},
                success:function(json){
                    // var data_arr = $.map(json.data, function(r) {
                    //     return {name: r.name,y: Number(r.y),show: r.y}
                    // });
                    // console.log(data_arr);
                    $(".time_source").html(json.name);
                    Controller.piechart(json, "pie", 'flow', 'flow');              
                }
            });
            $(document).on("click", ".input-search", function () {
                var jumpurl = window.location.origin + window.location.pathname + "?ref=addtabs&addtabs=1";
                if($("#start_date").val() != ''){
                    jumpurl += "&starttime="+$("#start_date").val();
                }
                if($("#end_date").val() != ''){
                    jumpurl += "&endtime="+$("#end_date").val();
                }
                if($("#typename").val() != ''){
                    jumpurl += "&typename="+$("#typename").val();
                }
                if ($("#compare").val() != null) {
                    jumpurl += "&compare="+$("#compare").val();
                }
                if ($("#ip").val() != null) {
                    jumpurl += "&ip="+$("#ip").val();
                }
                window.location.href = jumpurl;
            });
            $(document).on("click", ".input-reset", function () {
                var jumpurl = window.location.origin + window.location.pathname + "?ref=addtabs&addtabs=1";
                window.location.href = jumpurl;
            });
            $('select[name="typename"]').on('click',function(){
                    var typename = $(this).val();
                    // A点
                    // B点
                    // 国内节点统计
                    // 国外节点统计
                    if(typename == 1){
                        $("select[name='compare']").empty();
                        $("select[name='compare']").append('<option value="'+1 + '" >' + 'A点' + '</option>');
                        $("select[name='compare']").append('<option value="'+2 + '" >' + 'B点' + '</option>');
                    }else{
                        $("select[name='compare']").empty();
                        $("select[name='compare']").append('<option value="'+1 + '" >' + '国内节点统计' + '</option>');
                        $("select[name='compare']").append('<option value="'+2 + '" >' + '国外节点统计' + '</option>');
                    }
                });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        piechart: function(json, type, id ,idname){ //画图 饼图/趋势图   数据   类型(画图的字段后期可扩展)  id
            // console.log(json);
            // return false;
          var myChart = echarts.init(document.getElementById(id));
          var lengthdsname = [];
          for(var item of json.series) { // item代表数组里面的元素
            lengthdsname.push(item.name);
          };
          // console.log(lengthdsname);
          // var flowname=type;
          // if(flowname.length > 40){
          //   var temp = flowname.substring(0,40)+'...';
          // }else{
          //   temp = flowname;
          // }

          // $('#'+idname).html(temp);
          // $('#'+idname).attr("title", flowname);
          
          // var text= temp;
          var text= 'ssss';
          option = {
            tooltip: {
                trigger: 'axis',
                position:'inside',
                formatter:function(params, ticket, callback){
                    var tipString = params[0].name + "<br />";
                    var indexColor;
                    if(id.indexOf("property") != -1 ){
                        for (var i = 0, length = params.length; i < length; i++) {
                            if(params[i].value==""||params[i].value==null){
                                var item_val_str = 0+" %";
                            }else{
                                var item_val_str = params[i].value.toFixed(2)+" %";
                            }
                            indexColor = params[i].color;
                            tipString += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background:' + indexColor + '"></span>';
                            tipString += '<span style="color:#fff" data-type ="lineTip" data-val=' + params[i].value + '>' + params[i].seriesName + '：' + item_val_str + '</span><br />';
                        }
                    }else{
                        for (var i = 0, length = params.length; i < length; i++) {
                            var item_val = params[i].value;
                            if(item_val < 1024){
                                if(item_val==""||item_val==null){
                                    var item_val_str = 0+" bps";
                                }else{
                                    var item_val_str = item_val.toFixed(2)+" bps";
                                }
                               //var item_val_str = item_val.toFixed(2)+" bps";
                            }else if(1024 < item_val && item_val < 1024 * 1024){
                               var item_val_str = (item_val/(1024)).toFixed(2)+"Kbps";
                            }else if(1024 * 1024 <= item_val && item_val < 1024 * 1024 * 1024){
                               var item_val_str = (item_val/(1024*1024)).toFixed(2)+"Mbps";
                            }else if(1024 * 1024 * 1024 <= item_val && item_val < 1024 * 1024 * 1024 * 1024){
                               var item_val_str = (item_val/(1024*1024*1024)).toFixed(2)+"Gbps";
                            }
                            indexColor = params[i].color;
                            tipString += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background:' + indexColor + '"></span>';
                            tipString += '<span style="color:#fff" data-type ="lineTip" data-val=' + params[i].value / 1024 / 1024 + '>' + params[i].seriesName + '：' + item_val_str + '</span><br />';
                        }
                    }
                    return tipString;
                    
                }
            },
            /*title: {
                left: 'center',
                text: text,
            },*/
            legend: {
                x: 'center',
                y:30,
                data:lengthdsname
             },
            toolbox: {
                feature: {
                    myTool1: {
                            show: true,
                            title: '推送到屏幕',
                            // icon:'image:///assets/img/copy.png',
                            //icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
                            onclick: function (){
                                $.ajax({
                                    url: 'general/screens/index',
                                    type:'post',
                                    //data: {ids:tag_id,names:names,starttime:starttime3,endtime:endtime3,gradename:gradename3},
                                    dataType:'json',
                                    success:function(json){
                                        if(json.total<1){
                                            Toastr.error("请先到屏幕维护-配置屏幕页面，配置屏幕名称");
                                        }else{
                                            var tag_id = $("#ids").html();
                                            Fast.api.open("resources/tag/add_screen/ids/"+tag_id+"?from=tag","选择屏幕");
                                        }
                                    }
                                });
                            }
                    },
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    restore: {},
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data : json.xAxis,
            },
            yAxis: {
                type: 'value',
                boundaryGap: [0, '100%'],
                axisLabel: {
                    formatter:function(item_val){
                        if(id.indexOf("property") != -1 ){
                            return Math.floor(item_val) + ' %';
                        }else{
                            if(item_val < 1024){
                               return Math.floor(item_val)+" bps";
                            }else if(1024 < item_val && item_val < 1024 * 1024){
                               return Math.floor(item_val/(1024))+"Kbps";
                            }else if(1024 * 1024 <= item_val && item_val < 1024 * 1024 * 1024){
                               return Math.floor(item_val/(1024*1024))+"Mbps";
                            }else if(1024 * 1024 * 1024 <= item_val && item_val < 1024 * 1024 * 1024 * 1024){
                               return Math.floor(item_val/(1024*1024*1024))+"Gbps";
                            }
                        }    
                    },
                },
            },
            dataZoom: [{
                show:true,
                //type: 'inside',//鼠标滚动影响图标拖动
                type: 'slider',
                start: 85,
                end: 100,
                zoomOnMouseWheel:false,
            }, {
                start: 0,
                end: 10,
                handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                handleSize: '80%',
                handleStyle: {
                    color: '#fff',
                    shadowBlur: 3,
                    shadowColor: 'rgba(0, 0, 0, 0.6)',
                    shadowOffsetX: 2,
                    shadowOffsetY: 2
                }
            }],
            grid: [
                    { 
                      left: '7%',
                      right: '10%',
                      width: '91%'
                  }
                   
            ],
            series: [
                {
                    name:json.series[0].name,
                    type:'line',
                    smooth:true,
                    symbol: 'none',
                    sampling: 'average',
                    /*itemStyle: {
                        color: 'rgb(255, 70, 131)'
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: 'rgb(255, 158, 68)'
                        }, {
                            offset: 1,
                            color: 'rgb(255, 70, 131)'
                        }])
                    },*/
                    itemStyle: {
                        normal: {
                            //color: '#00aa00',
                            //color:'linear-gradient(top, white, red)',
                            opacity: 1,
                            barBorderRadius: 5,
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 1,
                                color: '#c8edc8'
                            }, {
                                offset: 0,
                                color: '#00aa00'
                            }])

                        }
                    },
                    areaStyle: {
                        normal: {
                        }
                    },
                    lineStyle: {
                        normal: {
                            color: '#047d04',
                            width: 1.5
                        }
                    },
                    data:json.series[0].data
                }
                ,{
                    name:json.series[1].name,
                    type:'line',
                    smooth:true,
                    symbol: 'none',
                    sampling: 'average',
                    /*itemStyle: {
                        color: 'rgb(255, 70, 131)'
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: 'rgb(255, 158, 68)'
                        }, {
                            offset: 1,
                            color: 'rgb(255, 70, 131)'
                        }])
                    },*/
                    itemStyle: {
                        normal: {
                            //color: '#002a97',
                            //color:'linear-gradient(top, white, red)',
                            opacity: 1,
                            barBorderRadius: 5,

                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 1,
                                color: '#9a9aff'
                            }, {
                                offset: 0,
                                color: '#002a97'
                            }])
                        }
                    },
                    areaStyle: {
                        normal: {
                        },
                    },
                    lineStyle: {
                        normal: {
                            color: '#03037b',
                            width: 1.5
                        }
                    },
                    data:json.series[1].data
                }
            ]
          };
         //使用刚指定的配置项和数据显示图表
          myChart.clear();
          myChart.setOption(option,true);
          window.addEventListener("resize", function () {
            myChart.resize();
          });
          myChart.dispatchAction({ // 默认启动 toolbox 中 dataZoom 的区域缩放状态
                type: "takeGlobalCursor",
                key: "dataZoomSelect",
                dataZoomSelectActive: true
          });
          setInterval(function () {
                if ($("#"+id).width() != $("#"+id+" canvas").width() && $("#"+id+" canvas").width() < $("#"+id).width()) {
                    myChart.resize();
                }
            }, 700);
          
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});